//
//  YWMissionDetailsViewController.m
//  maintain
//
//  Created by 郑想 on 16/1/11.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "MJextension.h"
#import "QRCodeReaderViewController.h"
#import "UIColor+CustomColors.h"
#import "UIView+Extension.h"
#import "YWAnimationView.h"
#import "YWBuildingManager.h"
#import "YWCommonTool.h"
#import "YWEquipment.h"
#import "YWEquipmentMaintenanceRecord.h"
#import "YWEquipmentManager.h"
#import "YWLocation.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWMaintenanceRecordDetailTableViewController.h"
#import "YWMission.h"
#import "YWMissionDetailsViewController.h"
#import "YWMissionManager.h"
#import "YWNavigationController.h"
#import "YWNotifyManager.h"
#import "YWNoQrcodeRights.h"

#import "YWScanEquipmentNotMatchVC.h"
#import "YWQrcodeManager.h"
#import "YWEquipmentFieldRecord.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"
#import "FTPopOverMenu.h"
#import "MBProgressHUD.h"

#import "YWDetailWorkTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
//#import "YWDoDeteAndUpKeepMissionTableViewController.h"
#import "YWDoDeteAndUpKeepEquTypeTableViewController.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWModifyDetectAndUpkeepTableViewController.h"
#import "YWDetectAndUpkeepReplyTableViewController.h"
#import "YWNoQrcodeSelectLocationTableViewController.h"
#import "YWSelectAtUserTableViewController.h"
#import "YWObserverTableViewController.h"
#import "YWReplyManager.h"
#import "YWReply.h"
#import "Masonry.h"

#import "YWObserveTableViewCell.h"
#import "YWNewReplyTableViewCell.h"
#import "YWMeterReadingDetailRecordCell.h"

#define finishInfoLabelH (50)

@interface YWMissionDetailsViewController () <UITableViewDelegate, UITableViewDataSource,YWSelectAtUserTableViewDelegate,UITextFieldDelegate>{
    NSString *replyContent;
}
@property (nonatomic, weak) UILabel* allEquipmentCountLabel;
@property (nonatomic, weak) UILabel* completeEquipmentCountLabel;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, weak) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* sourceData;

@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UIButton *noScanButton;
@property (nonatomic, strong) UIButton *doButton;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) UIView *replyView;//回复栏
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@end

@implementation YWMissionDetailsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"missionDetail", nil);//@"任务详情";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    [self.navigationController.view addSubview:self.replyView];
    if (!_isFromRecord && self.mission.creator.uniqueId == [YWLoginTool loginUser].uniqueId && self.mission.missionStatus == YWMissionStatusUnfinished) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"• • • " style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButtonEvent:event:)];
    }
    
    [self addBottomScanButtonView];
    
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(updateView:)];
    if (_mission.missionId > 0 && _mission.status!=-1) {
        //请求记录
        [self requestRecordList];
    }
    if (_mission.missionId > 0) {
        YWWeakSelf(weakSelf);
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(_mission.missionId).stringValue type:YWReplyRelationTypeDetectAndUpkeep WithComplete:^(BOOL success) {
            weakSelf.sourceData = nil;
            [weakSelf.tableView reloadData];
        }];
    }
}
#pragma mark -private methods
- (NSArray*)sourceData
{
    if (!_sourceData) {
        _sourceData = [NSMutableArray array];
        NSDictionary* recordsDir = [YWDetectAndUpkeepManager detectAndUpkeepRecordsWithMission:_mission];
        for (NSNumber* locationIdNumber in recordsDir.allKeys) {
            NSArray* records = [recordsDir objectForKey:locationIdNumber];
            if (records.count > 0) {
                NSString* locationName = [[YWBuildingManager shareManager] areaLocationNobuildingWithId:[locationIdNumber integerValue]];
                CGFloat locationLabelH = [YWCommonTool getHeightOfLabel:locationName andWidth:SCREEN_WIDTH - 2 * 15 andFont:KSmallContentFont andMinHeight:kMinLabelH];
                NSDictionary* dataDir = @{ @"locationH" : @(locationLabelH + 16),
                                           @"locationName" : locationName ?: NSLocalizedString(@"none", nil),
                                           @"record" : records };
                [_sourceData addObject:dataDir];
            }
        }
    }
    return _sourceData;
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:self.mission.missionId andRelationType:YWReplyRelationTypeDetectAndUpkeep];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (UILabel*)allEquipmentCountLabel
{
    if (!_allEquipmentCountLabel) {
        UILabel* allEquipmentCountLabel = [[UILabel alloc] init];
        allEquipmentCountLabel.textColor = [UIColor customTextGrayColor];
        allEquipmentCountLabel.font = KTitleFont;
        [self.headView addSubview:allEquipmentCountLabel];
        _allEquipmentCountLabel = allEquipmentCountLabel;
    }
    return _allEquipmentCountLabel;
}

- (UILabel*)completeEquipmentCountLabel
{
    if (!_completeEquipmentCountLabel) {
        UILabel* completeEquipmentCountLabel = [[UILabel alloc] init];
        completeEquipmentCountLabel.textColor = [UIColor customTextGrayColor];
        completeEquipmentCountLabel.font = KTitleFont;

        [self.headView addSubview:completeEquipmentCountLabel];
        _completeEquipmentCountLabel = completeEquipmentCountLabel;
    }
    return _completeEquipmentCountLabel;
}

- (UIView *)headView{
    if (!_headView) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        _headView = view;
    }
    return _headView;
}


- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        if (self.maintenanceType == YWMaintenanceTypeDetection) {
        //            [scanButton setImage:[UIImage imageNamed:@"detection_normal"] forState:UIControlStateNormal];
        //        } else{
        //            [scanButton setImage:[UIImage imageNamed:@"upkeep_normal"] forState:UIControlStateNormal];
        //        }
        //scanButton.layer.masksToBounds = YES;
        [button setTitle:NSLocalizedString(@"scanQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(handleScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:NSLocalizedString(@"noQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

- (UIButton *)doButton{
    if (!_doButton) {
        UIButton* doButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [doButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [doButton setBackgroundColor:[UIColor customBlueColor]];
        [doButton setTitle:NSLocalizedString(@"doMission", nil) forState:UIControlStateNormal];
        [doButton addTarget:self action:@selector(handleDoBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        doButton.frame = CGRectMake(0, SCREEN_HEIGHT-64-kButtonH, SCREEN_WIDTH, kButtonH);
        _doButton = doButton;
    }
    return _doButton;
}

- (void)addBottomScanButtonView{
    if (!self.isFromMatchMissionVC) {
        [self.noScanButton removeFromSuperview];
        [self.scanButton removeFromSuperview];
        if (!(self.mission.missionStatus == YWMissionStatusFinished || self.mission.missionStatus == YWMissionStatusExpire || ([self.mission.executorIds rangeOfString:[@([YWLoginTool loginUser].uniqueId) stringValue]].location == NSNotFound))) {
            [self.view addSubview:self.noScanButton];
            [self.view addSubview:self.scanButton];
        }
//        else{
//            
//        }
    }else{
        if (self.mission.missionStatus == YWMissionStatusFinished) {
            [self.doButton setBackgroundColor:[UIColor lightGrayColor]];
        }
        [self.view addSubview:self.doButton];
    }
    
}

- (void)requestRecordList
{
    YWWeakSelf(weakSelf);
    [YWDetectAndUpkeepManager requestMissionRecordWithMission:_mission completeBlock:^(NSInteger count) {
        weakSelf.sourceData = nil;
        [weakSelf.tableView reloadData];
    }];
}

- (UITableView*)tableView
{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor customBackgroudColor];
        
        [tableView registerClass:[YWDetailWorkTableViewCell class] forCellReuseIdentifier:YWDetailWorkTableViewCellIdentifier];
        [tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
        [tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
        [tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        tableView.separatorColor = [UIColor blackColor];
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}
- (void)handleDoBtnEvent:(id)sender{
    if (_mission.status == -1) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionHasCancel", nil)];
        return;
    }
    if (_mission.missionStatus == YWMissionStatusFinished) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsFinished", nil)];
        return;
    }else if (_mission.missionStatus == YWMissionStatusExpire){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsExpired", nil)];
        return;
    }
    YWDoDeteAndUpKeepEquTypeTableViewController * doDeteMissionVC = [[YWDoDeteAndUpKeepEquTypeTableViewController alloc] init];
    doDeteMissionVC.qrCodeId = self.qrCodeId;
    doDeteMissionVC.locationId = self.locationId;
    doDeteMissionVC.maintenanceMission = self.mission;
    [self.navigationController pushViewController:doDeteMissionVC animated:YES];
}

- (void)handleNoScanBtnEvent:(id)sender{
    NSInteger value = 0;
    if (_mission.maintenanceTypeId == YWMaintenanceTypeDetection) {
        value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeDetectionKey] integerValue];
    }else{
        value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeUpkeepKey] integerValue];
    }
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"cantDoMissionWithoutPermission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        if (self.mission.status == -1) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionHasCancel", nil)];
            return;
        }
        if (self.mission.missionStatus == YWMissionStatusFinished) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsFinished", nil)];
            return;
        }else if (self.mission.missionStatus == YWMissionStatusExpire){
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsExpired", nil)];
            return;
        }
        YWNoQrcodeSelectLocationTableViewController *noQrcodeSlecetLocationVC = [[YWNoQrcodeSelectLocationTableViewController alloc] init];
        __weak __typeof(&*noQrcodeSlecetLocationVC) weakNoQrcodeSlecetLocationVC = noQrcodeSlecetLocationVC;
        noQrcodeSlecetLocationVC.maintenanceType = self.mission.maintenanceTypeId;
        noQrcodeSlecetLocationVC.isDoTempMission = NO;
        noQrcodeSlecetLocationVC.buildingId = self.mission.buildingId;
        noQrcodeSlecetLocationVC.doMissionBlock = ^(NSInteger locationId) {
            __strong __typeof(&*weakNoQrcodeSlecetLocationVC) strongNoQrcodeSlecetLocationVC = weakNoQrcodeSlecetLocationVC;
            [self doMission:self.mission qrCodeId:nil noScanQrcodeLocationId:locationId wReader:strongNoQrcodeSlecetLocationVC];
        };
        noQrcodeSlecetLocationVC.missionId = self.mission.missionId;
        noQrcodeSlecetLocationVC.equipmentTypeId = self.mission.equipmentTypeId;
        [self.navigationController pushViewController:noQrcodeSlecetLocationVC animated:YES];
    }
}

- (void)handleScanBtnEvent:(id)sender{
    if (self.mission.status == -1) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionHasCancel", nil)];
        return;
    }
    if (self.mission.missionStatus == YWMissionStatusFinished) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsFinished", nil)];
        return;
    }else if (self.mission.missionStatus == YWMissionStatusExpire){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionIsExpired", nil)];
        return;
    }
    YWMaintenanceMission *weakMission = self.mission;
    [[YWQrcodeManager shareManager]clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                [self doMission:weakMission qrCodeId:qrcodeId noScanQrcodeLocationId:self.locationId wReader:self];
            }];
        });
    }];
}

-(void)doMission:(YWMaintenanceMission*)weakMission qrCodeId:(NSString*)qrCodeId noScanQrcodeLocationId:(NSInteger)noScanQrcodeLocationId wReader:(UIViewController*)viewController{
    YWMissionScanQrcodeStatus missionScanQrcodeStatus = [[YWMissionManager shareManager] judgeScanMatchMission:weakMission qrcodeId:qrCodeId orNoScanQrcodeLocationId:noScanQrcodeLocationId];
    if (missionScanQrcodeStatus == YWMissionScanQrcodeStatusMatch) {
        YWDoDeteAndUpKeepEquTypeTableViewController * doDeteMissionVC = [[YWDoDeteAndUpKeepEquTypeTableViewController alloc] init];
        doDeteMissionVC.qrCodeId = qrCodeId;
        doDeteMissionVC.locationId = noScanQrcodeLocationId;
        doDeteMissionVC.maintenanceMission = weakMission;
        [viewController.navigationController pushViewController:doDeteMissionVC animated:YES];
    }else {
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        NSString *showContent = nil;
        if (qrCodeId) {
            showContent = NSLocalizedString(@"theQRCodeNotMatchTheMission", nil);//@"此二维码与任务不匹配,请扫描其它的二维码";
        }else{
            showContent = NSLocalizedString(@"theLocationNotMatchTheMission", nil);//@"此位置与任务不匹配,请重新选择";
        }
        senmVC.showContent = showContent;
        [viewController.navigationController pushViewController:senmVC animated:YES];
    }
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return UITableViewAutomaticDimension;
//        [tableView fd_heightForCellWithIdentifier:YWDetailWorkTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetailWorkTableViewCell *cell) {
//            [self configureCell:cell atIndexPath:indexPath];
//        }];
    }else{
        return 50;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.sourceData.count + 2;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        if (self.replyArray.count>0) {
            return [self.replyArray count] + 2;//参与人+“评论”
        }else{
            return 1;
        }
    }
    NSDictionary* dic = self.sourceData[section - 2];
    NSArray* records = [dic objectForKey:@"record"];
    return records.count;
}

#pragma mark - configure cell
- (void)configureCell:(YWDetailWorkTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.maintenanceMission = _mission;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        YWDetailWorkTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:YWDetailWorkTableViewCellIdentifier];
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.maintenanceMission = _mission;//参与人cell
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"评论%@:",count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.replyArray[indexPath.row-2];
            cell.reply = reply;
            return cell;
        }
    }
    
    NSUInteger section = [indexPath section] - 2;
    NSUInteger row = [indexPath row];

    static NSString* GroupedTableIdentifier = @"YWMissionDetailViewTableViewCellIdentifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:GroupedTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
              initWithStyle:UITableViewCellStyleSubtitle
            reuseIdentifier:GroupedTableIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
    }
    NSDictionary* dic = self.sourceData[section];
    NSArray* records = [dic objectForKey:@"record"];
    if (_mission.equipments.count==0) {//_mission.type == YWMissionTypeManually
        if (records.count > row) {
            YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)records[row];
            YWEquipment* equipment = [[YWEquipmentManager shareManager] equipmentWithId:record.equipmentId];
            cell.textLabel.text = equipment.equipmentName.length?equipment.equipmentName:NSLocalizedString(@"unknowEquipment", nil);
            cell.textLabel.textColor = [UIColor blackColor];
            NSString *timeStr = [YWCommonTool showDateAndTime:record.completeTime / 1000];
            cell.detailTextLabel.text = record.handlerName.length>0?[NSString stringWithFormat:@"%@ %@",record.handlerName,timeStr]:timeStr;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }else{
        if (records.count > row) {
            NSDictionary *dic = records[row];
            NSString *equipmentName = [dic objectForKey:@"equipmentName"];
            NSString *equipmentOwnCode = [dic objectForKey:@"equipmentOwnCode"];
            YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)[dic objectForKey:@"record"];
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",equipmentName.length?equipmentName:NSLocalizedString(@"unknowEquipment", nil),equipmentOwnCode];
            
            if ([record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
                NSString *timeStr = [YWCommonTool showDateAndTime:record.completeTime / 1000];
                cell.detailTextLabel.text = record.handlerName.length>0?[NSString stringWithFormat:@"%@ %@",record.handlerName,timeStr]:timeStr;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.textLabel.textColor = [UIColor blackColor];
            }else{
                cell.textLabel.textColor = [UIColor customTextGrayBlackColor];
                NSString *typeName = _mission.maintenanceTypeId == YWMaintenanceTypeDetection ? NSLocalizedString(@"detection", nil): NSLocalizedString(@"upkeep", nil);
                cell.detailTextLabel.text = [NSString stringWithFormat:@"未%@",typeName];
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (!_isFromRecord) {
        if (section!=0) {
            return nil;
        }
        static NSString* HeaderIdentifier = @"YWCirculatonDetailVCForHeaderInSection";
        UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
        if (headerView == nil) {
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
            headerView.contentView.backgroundColor = [UIColor whiteColor];
            UIView *line = [[UIView alloc] init];
            line.frame = CGRectMake(0, 23, SCREEN_WIDTH, 1);
            line.backgroundColor = [UIColor customLineColor];
            [headerView addSubview:line];
            //评论
            UILabel *replyLabel = [[UILabel alloc] init];
            replyLabel.textAlignment = NSTextAlignmentLeft;
            replyLabel.textColor = [UIColor customTextGrayColor];
            replyLabel.tag = 2006;
            replyLabel.font = KSmallContentFont;
            replyLabel.userInteractionEnabled = YES;
            [replyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
            [headerView addSubview:replyLabel];
            
            UIImageView *replyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"remind_replyIcon"]];
            replyImageView.tag = 2006;
            replyImageView.userInteractionEnabled = YES;
            [replyImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
            [headerView addSubview:replyImageView];
            
            [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(line.mas_top);
                make.width.mas_equalTo(@23);
                make.height.mas_equalTo(@23);
            }];
            [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(replyImageView.mas_top);
                make.left.mas_equalTo(replyImageView.mas_right).offset(8);
                make.right.mas_equalTo(headerView.mas_right).offset(-8);
                make.bottom.mas_equalTo(replyImageView.mas_bottom);
                make.width.mas_lessThanOrEqualTo(@90);
            }];
            //参与者
            UILabel *observerLabel = [[UILabel alloc] init];
            observerLabel.textAlignment = NSTextAlignmentLeft;
            observerLabel.textColor = [UIColor customTextGrayColor];
            observerLabel.tag = 2007;
            observerLabel.font = KSmallContentFont;
            observerLabel.userInteractionEnabled = YES;
            [observerLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
            [headerView addSubview:observerLabel];
            
            UIImageView *observerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_invite"]];
            observerView.tag = 2007;
            observerView.userInteractionEnabled = YES;
            [observerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
            [headerView addSubview:observerView];
            
            [observerView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(line.mas_top);
                make.width.mas_equalTo(@23);
                make.height.mas_equalTo(@23);
            }];
            [observerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(observerView.mas_top);
                make.left.mas_equalTo(observerView.mas_right).offset(8);
                make.right.mas_equalTo(replyImageView.mas_left).offset(-8);
                make.bottom.mas_equalTo(observerView.mas_bottom);
                make.width.mas_lessThanOrEqualTo(@90);
            }];
            
        }
        UILabel* label = [headerView viewWithTag:2006];
        label.text = NSLocalizedString(@"comment", nil);//@"评论";
        
        //参与者
        label = [headerView viewWithTag:2007];
        label.text = NSLocalizedString(@"invitation", nil);//@"邀请";
        return headerView;
    }else{
        return nil;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1 || section == 0) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWMissionDetailViewTableViewForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 1004;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSDictionary* dic = self.sourceData[section - 2];
    CGFloat locationH = [[dic objectForKey:@"locationH"] floatValue];

    NSString* locationName = [dic objectForKey:@"locationName"];
    UILabel* label = [headerView viewWithTag:1004];
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, locationH);
    label.text = locationName.length?locationName:@"";

    return headerView;
}
- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
    if (!_isFromRecord) {
        return section != 0 ? 1 : 24;
    }else{
        return 0.0;
    }
}
#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 0;
    }
        NSDictionary* dic = self.sourceData[section - 2];
        CGFloat locationH = [[dic objectForKey:@"locationH"] floatValue];
        return locationH;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
        if (!_isFromRecord) {
            if (self.mission.missionId>0) {
                YWDetectAndUpkeepReplyTableViewController *detectAndUpkeepReplyVC = [[YWDetectAndUpkeepReplyTableViewController alloc] init];
                detectAndUpkeepReplyVC.mission = self.mission;
                [self.navigationController pushViewController:detectAndUpkeepReplyVC animated:YES];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"tempMissonCannotReply", nil)];
            }
        }
        
    }else if (indexPath.section != 0 && indexPath.section !=1){
        NSUInteger section = [indexPath section];
        NSUInteger row = [indexPath row];
        
        NSDictionary* dic = self.sourceData[section - 2];
        NSArray* records = [dic objectForKey:@"record"];
        if (_mission.equipments.count==0) {//_mission.type == YWMissionTypeManually
            if (records.count > row) {
                YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)records[row];
                YWMaintenanceRecordDetailTableViewController* maintenanceVC = [[YWMaintenanceRecordDetailTableViewController alloc] init];
                record.maintenanceTypeId = _mission.maintenanceTypeId;
                maintenanceVC.maintenanceRecord = record;
                [self.navigationController pushViewController:maintenanceVC animated:YES];
            }
        }else{
            if (records.count > row) {
                NSDictionary *dic = records[row];
                YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)[dic objectForKey:@"record"];
                if ([record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
                    YWMaintenanceRecordDetailTableViewController* maintenanceVC = [[YWMaintenanceRecordDetailTableViewController alloc] init];
                    record.maintenanceTypeId = _mission.maintenanceTypeId;
                    maintenanceVC.maintenanceRecord = record;
                    [self.navigationController pushViewController:maintenanceVC animated:YES];
                }
            }
        }
    }
}

#pragma mark - 评论、邀请、分享等响应事件
- (void)handleReplyLabelTapEvent:(id)sender{
    [self.textField becomeFirstResponder];
}

- (void)handleObserverLabelTapEvent:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters = self.mission.creator?@[self.mission.creator]:nil;
    observerVC.executors = self.mission.executors;
    observerVC.observers = self.mission.observers;
    observerVC.relationId = [@(self.mission.missionId) stringValue];
    observerVC.type = YWReplyRelationTypeDetectAndUpkeep;
    [self.navigationController pushViewController:observerVC animated:YES];
}

#pragma mark notifa
- (void)updateView:(NSNotification*)noti
{
    if ([noti.object isKindOfClass:[YWMaintenanceMission class]]) {
        YWMaintenanceMission* updateMission = (YWMaintenanceMission*)noti.object;
        if (_mission.missionId == updateMission.missionId) {
            _mission = updateMission;
            if (_mission.missionStatus == YWMissionStatusFinished) {
                [self addBottomScanButtonView];
            }
            _sourceData = nil;
            [self.tableView reloadData];
        }
        if (self.mission.missionStatus == YWMissionStatusFinished) {
            self.navigationItem.rightBarButtonItem = nil;
        }
    }
}
- (void)clickRightBarButtonEvent:(UIBarButtonItem *)sender event:(UIEvent *)event{
    [FTPopOverMenu showFromEvent:event
                        withMenu:@[NSLocalizedString(@"modify", nil),NSLocalizedString(@"delete", nil)]
                  imageNameArray:@[@"menu_edit",@"menu_delete"]
                       doneBlock:^(NSInteger selectedIndex) {
                           if (selectedIndex==0) {
                               YWModifyDetectAndUpkeepTableViewController *modifyVC = [[YWModifyDetectAndUpkeepTableViewController alloc] init];
                               modifyVC.mission = self.mission;
                               [self.navigationController pushViewController:modifyVC animated:YES];
                           }else{
                               UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToDelete", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
                               [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
                               [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                   [self.HUD show:YES];
                                   [YWDetectAndUpkeepManager requestDeleteMission:self.mission.missionId maintenanceType:self.mission.maintenanceTypeId completeBlock:^(BOOL success) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [self.HUD hide:YES];
                                           if (success) {
                                               [self.navigationController popViewControllerAnimated:YES];
                                           }
                                       });
                                   }];
                               }]];
                               [self presentViewController:alert animated:YES completion:nil];
                               
                           }
                       } dismissBlock:nil];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        _replyView.hidden = YES;
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40-15, 40)];
    self.textField.placeholder = NSLocalizedString(@"reply", nil);
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, 40, 40);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    //创建人
    if (self.mission.creator) {
        [allUser addObject:self.mission.creator];
    }
    //执行人
    [allUser addObjectsFromArray:self.mission.executors];
    //observer
    [allUser addObjectsFromArray:self.mission.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeReplyContent", nil)];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replyContentLengthCannotMoreThan100", nil)];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    replyContent = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replySucceed", nil)];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            _sourceData = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _mission.missionId;
    reply.relationType = YWReplyRelationTypeDetectAndUpkeep;
    reply.content = replyContent;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.mission.observers];
        [tempArray addObject:handler];
        self.mission.observers = [NSArray arrayWithArray:tempArray];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.mission.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.mission.observers];
            [tempArray removeObject:handler];
            self.mission.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
